import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { config} from '../../../shared/smartadmin.config';
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
declare var $: any;
declare var BMap: any;
declare var toMapPoint: any;
@Component({
  selector: 'sa-rail-bind-page',
  templateUrl: './rail-bind-page.component.html',
})
export class RailBindPageComponent implements OnInit {
	tableData:any = []; //table数据
	totalCount:number = 0; //分页总条数
	curPage:number = 1; //分页当前页
	paramCurPage:any;//记录url传过的页码
	pageSize:number = 10; //内置的分页每页条数
	fixPageSize:number = 10; //扩展的pagesize控制
	searchKey:string = ''; //搜索keyword
	deviceId:string = '';//设备ID
	selectedCarNumber:string='';
	selectedCompanyId:string = '';
	selectedCompanyName:string = '';
	companyId:string = '';
	railType:string = '';//围栏类型
	railName:string = '';//围栏名称
	activeSelected:string='';//围栏选中id
	myIcon1:any;//围栏圆形标志
	myIcon2:any;//围栏多边形标志
	map:any;//地图
	carId:string = '';//需要配置的车辆id
	mapMarkerCar:string = '';//需要配置的车牌
	mapMarkerCarArr:any[] = [];
	constructor(private jsonApiService: JsonApiService,private router: Router,private activatedRoute: ActivatedRoute,) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.carId = queryParams.id;
			this.paramCurPage = queryParams.nowPage;
			this.mapMarkerCar = queryParams.car;
		});
	}
	//刷新
	refresh(){
		this.load();
	}
	ngOnInit() {
		if(this.mapMarkerCar){
			this.mapMarkerCarArr = this.mapMarkerCar.split(',');
		}
		this.load();
		this.initBMap();
	}
	//初始化百度地图
	initBMap(){
		var map = new BMap.Map("baiduMap",{enableMapClick: false});    // 创建Map实例
		this.map = map;
		map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
		var myCity = new BMap.LocalCity();//获取用户当前所在城市
		myCity.get(function (result){
			let point=result.center;
		  	let city = new BMap.Point(point.lng, point.lat); //创建点坐标
		  	map.centerAndZoom(city, 12); //初始化地图，设置中心点坐标和地图级别
		});
		this.myIcon1 = new BMap.Icon("assets/img/deployIcon/icon3.png", new BMap.Size(30, 30), {
			imageOffset: new BMap.Size(10, 0)
		}); //圆形的marker图标
		this.myIcon2 = new BMap.Icon("assets/img/deployIcon/icon4.png", new BMap.Size(30, 30), {
			imageOffset: new BMap.Size(10, 0)
		}); //多边形的marker图标
		this.initRailData();
	}
	//初始化围栏数据
	initRailData(){
		this.jsonApiService.http2('mapmarker/getmarker.html', '').subscribe(result => {
			let len = result.data.length;
			if(len < 1) {
				return;
			}
			for(var i = 0; i < len; i++) {
				var obj = toMapPoint(result.data[i]);
				var point = new BMap.Point(obj.lng, obj.lat);
				var marker = new BMap.Marker(point, {
					icon: this.myIcon2
				});
				if(obj.lnglats == '') {
					marker = new BMap.Marker(point, {
						icon: this.myIcon1
					});
				}
				var myGraph  = this.wgsGraphical(obj, false);
				this.map.addOverlay(marker);
				this.map.addOverlay(myGraph);
			}
		})
	}
	//大地坐标系转成百度坐标系后绘图
	wgsGraphical(obj, color) {
		var myGraph;
		if(color) {obj.color = color}
		if(obj.lnglats == ''||obj.lnglats == null) {
			var point = new BMap.Point(obj.lng, obj.lat);
			myGraph = new BMap.Circle(point, obj.radius, {
				strokeColor:'blue',
				fillColor:'red',
				strokeWeight:1,
				strokeOpacity:0.2,
				fillOpacity:0.2
			}); //创建圆
		}else{
			if(!obj.lnglats){return;}
			var poitnArr = [];
			var lnglatsArr = obj.lnglats.split(';');
			for(var j = 0; j < lnglatsArr.length; j++) {
				if(lnglatsArr[j] !== "") {
					var arr = lnglatsArr[j].split(',');
					var point=toMapPoint({lng:arr[0], lat:arr[1]});
					poitnArr.push(new BMap.Point(point.lng,point.lat))
				}
			}
			myGraph = new BMap.Polygon(poitnArr, {
				strokeColor:'blue',
				fillColor:'red',
				strokeWeight:1,
				strokeOpacity:0.2,
				fillOpacity:0.2
			}); //创建多边形
		}
		return myGraph;
	}
	ngOnDestroy(){
	}
	//查询
	search_data(){
		this.searchKey = common.stringTrim(this.searchKey);
		this.load();
	}
	//加载list数据
	load(){
		var postData={
			pageSize:this.pageSize,
			nowPage:this.curPage,
			parameters:{
				name:common.stringTrim(this.railName),
				typeId:this.railType
			}
		}
		let reqdata='gridPager='+JSON.stringify(postData);
		this.jsonApiService.http("mapmarker/markerpagelist.html", reqdata).subscribe(data => {
			if(data.isSuccess){
				this.tableData = data.exhibitDatas;
				this.totalCount = data.recordCount;
			}
		})
	}
	rowSelectEvent(row){
		this.activeSelected=row.id;
		var pp=toMapPoint({lng:row.lng,lat:row.lat});
		let positionPoint = new BMap.Point(pp.lng, pp.lat); //创建点坐标
        this.map.centerAndZoom(positionPoint, 12); //初始化地图，设置中心点坐标和地图级别
        let typeName = '--',name = row.name?row.name:'--',
        company = row.companyEntity?row.companyEntity.companyName:'--',
        typeId = row.typeId?row.typeId:'--';
        if(typeId ==='1'){
        	typeName = '装货点';
        }else if(typeId ==='2'){
        	typeName = '卸货点';
        }
		let content = '<div><ul>' +
			'<li style="margin-top:3px">标注名称：'+ name +'<li>' +
			'<li style="margin-top:8px">所属公司：'+ company +'<li>' +
			'<li style="margin-top:4px">类型：'+ typeName +'<li>' +
			'</ul></div>';
		var infoWindow = new BMap.InfoWindow(content,{
			width: 200,
			heigth: 300
		}); // 创建信息窗口对象 
		
        this.map.openInfoWindow(infoWindow,positionPoint); //开启信息窗口
        setTimeout(function() {
	        if($('.pointer').length<1){
	        	$('.BMap_bottom').append('<div class="pointer"></div>');
	        }
		}, 50);
        
	}
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.load();
	}
	//  分页pageSize回调事件
	updatePageSize(e) {
		this.curPage = 1;
		this.pageSize = parseInt(e);
		this.load();
	}
	//围栏绑定
	rail_bind(){
		let reqdata = "carId="+this.carId+"&mapMarkerId="+this.activeSelected;
		this.jsonApiService.http('mapmarker/addCarMapMarkerConfig.html',reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if(data.success){
				this.router.navigate(['/data-statistics/rail/rail-bind'],{ queryParams: {nowPage:this.paramCurPage}});
			}
				
		})
	}
	goBack(){
		this.router.navigate(['/data-statistics/rail/rail-bind'],{ queryParams: {nowPage:this.paramCurPage}})
	}
}
